/**
 * 
 */
package com.detroitchow2.tasks;

import java.lang.reflect.Type;
import java.util.ArrayList;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

import com.detroitchow2.api.IFetchArticlesObserver;
import com.detroitchow2.util.LogUtil;
import com.detroitchow2.vo.Article;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.os.AsyncTask;

/**
 * @author dave
 *
 */
public class FetchArticlesTask extends AsyncTask<String, Void, ArrayList<Article>>
{

  private final String GET_ARTICLES_URL="http://detroitchow.com/getArticles.php?v=1&storeid=";
  private IFetchArticlesObserver observer;
  public FetchArticlesTask(IFetchArticlesObserver arg) {
    // TODO Auto-generated constructor stub
    observer = arg;
  }

  private void onFetchComplete(ArrayList<Article> articles) {
    observer.onFetchArticles(articles);
  }
  
  @Override
  protected void onPostExecute(ArrayList<Article> articles) {
    // TODO Auto-generated method stub
    super.onPostExecute(articles);
    onFetchComplete(articles);
  }
  
  @Override
  protected ArrayList<Article> doInBackground(String... params) {
    ArrayList<Article> result=null;
    String requestContent;
    HttpClient httpclient = new DefaultHttpClient();
    String requestUrl = GET_ARTICLES_URL + params[0];
   // LogUtil.log("FetchArticleTask doInBackground", "requestUrl: " + requestUrl);
    HttpGet request = new HttpGet(requestUrl);
    ResponseHandler<String> handler = new BasicResponseHandler();
    Gson gson = new Gson();
    Type resultType = new TypeToken<ArrayList<Article>>(){}.getType();
    try {
      requestContent = httpclient.execute(request, handler);  
      result = gson.fromJson(requestContent, resultType);
     // LogUtil.log("FetchArticleTask doInBackground", "result: " + result.size());
       
    }catch(Exception e){
      LogUtil.log("FetchArticlesTask doInBackground", e.getMessage());
    }
    httpclient.getConnectionManager().shutdown();
    
    return result;
  }

}
